using System;
using System.Collections.Generic;
using Project.ViewModels;
using Project.Views.Abstractions;
using UnityEngine;

namespace Project.Views
{
    public class WorldInventoryUIView : MonoUIViewBase<WorldInventoryViewModel>, IDisposable
    {
        private List<SlotUIView> _slotViews;

        [SerializeField] private Transform _slotsContainer;
        [Space]
        [SerializeField] private GameObject _slotPrefab;

        public void Dispose()
        {
            ViewModel.SlotViewModels.ElementAdded -= CreateSlot;
        }

        protected override void OnAfterInitialization()
        {
            for (int i = _slotsContainer.childCount - 1; i >= 0; i--)
                DestroyImmediate(_slotsContainer.GetChild(i).gameObject);

            _slotViews = new List<SlotUIView>();

            for (int i = 0, length = ViewModel.SlotViewModels.Count; i < length; i++)
                CreateSlot(i, ViewModel.SlotViewModels[i]);

            ViewModel.SlotViewModels.ElementAdded += CreateSlot;
        }

        private void CreateSlot(int index, SlotViewModel slotViewModel)
        {
            var slotObject = Instantiate(_slotPrefab, _slotsContainer);
            var slotView = slotObject.GetComponent<SlotUIView>();

            slotObject.name = $"{_slotPrefab.name}_{index}";
            slotObject.transform.SetSiblingIndex(index);

            _slotViews.Insert(index, slotView);

            slotView.Initialize(slotViewModel, RootUIView);
        }
    }
}
